<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- table区域 -->
      <el-table :data="userList" style="width: 100%" border stripe v-loading="loading">
        <el-table-column type="index" label="索引"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="editUserFormBtn(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              slot="reference"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                circle
                @click="openSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="closeAddUserForm"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserBtn">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑用户对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogVisible"
        width="30%"
        @close="closeEditUserForm"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="editUserForm"
          :rules="editUserFormRules"
          ref="editUserFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserBtn">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="30%" @close="cancelSetRole">
        <div>
          <p>当前的用户：{{setRoleUserInfo.username}}</p>
          <p>当前的角色：{{setRoleUserInfo.role_name}}</p>
        </div>
        <p>
          分配新角色：
          <template>
          <el-select v-model="selectedRoleId" placeholder="请选择" :clearable="true">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
          </template>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelSetRole">取 消</el-button>
          <el-button type="primary" @click="sureSetRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 邮箱验证规则
    var addUserEmailRule = (rule, value, callback) => {
      var reg = /^([A-Za-z0-9_-])+@([A-Za-z0-9_-])+\.([A-Za-z]{2,4})$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱不符合规则'))
      }
      callback()
    }
    // 验证手机号的规则
    var addUserMoblieRule = (rule, value, callback) => {
      var reg = /^[1](3|[5-9])\d{9}$/
      if (!reg.test(value)) {
        return callback(new Error('手机号码不符合规则'))
      }
      callback()
    }
    return {
      // user页面需求
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户数据
      userList: [],
      // 总用户数
      total: 0,
      // 加载动画
      loading: true,
      // 添加用户弹出框
      addDialogVisible: false,
      // 编辑用户弹出框
      editDialogVisible: false,
      // 添加用户信息
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: addUserEmailRule,
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: addUserMoblieRule, trigger: 'blur' }
        ]
      },
      // 编辑用户信息
      editUserForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 编辑用户规则
      editUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: addUserEmailRule,
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: addUserMoblieRule, trigger: 'blur' }
        ]
      },
      // 分配角色对话框开关
      setRoleDialogVisible: false,
      // 分配角色当前用户
      setRoleUserInfo: {
        username: '',
        role_name: ''
      },
      // 所有角色
      rolesList: [],
      // 选择的角色ID
      selectedRoleId: '',
      // 选择更改角色的用户ID
      setRoleCuurrentId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      this.loading = true
      const res = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        this.$message({
          message: res.meta.msg,
          type: 'error',
          duration: 1000
        })
        return
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 改变用户状态
    async changeState (userInfo) {
      const res = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message({
          message: '设置状态失败',
          type: 'error',
          duration: 1000
        })
      }
      this.$message({
        message: res.meta.msg,
        type: 'success',
        duration: 1000
      })
    },
    // 改变每页数量
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 改变当前页
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 关闭表单时重置
    closeAddUserForm () {
      // 重置表单
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户按钮
    addUserBtn () {
      // 调用表单验证
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message({
            type: 'error',
            message: '请填写完整用户信息'
          })
        }
        const res = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) {
          return this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
        this.$message({
          type: 'success',
          message: res.meta.msg
        })
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    async deleteUser (id) {
      const confirmRes = await this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch((err) => err)
      if (confirmRes !== 'confirm') {
        return this.$message({
          type: 'warning',
          message: '取消删除'
        })
      }
      const res = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: res.meta.msg
        })
      }
      this.$message({
        type: 'success',
        message: res.meta.msg
      })
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    // 关闭编辑用户框
    closeEditUserForm () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 编辑用户
    editUserFormBtn (userInfo) {
      this.editDialogVisible = true
      this.$nextTick(() => {
        Object.assign(this.editUserForm, userInfo)
      })
    },
    // 确认编辑用户
    editUserBtn () {
      // 调用表单验证
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message({
            type: 'error',
            message: '请填写完整用户信息'
          })
        }
        const res = await this.$http.put(
          'users/' + this.editUserForm.id,
          this.editUserForm
        )
        if (res.meta.status !== 200) {
          return this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
        this.$message({
          type: 'success',
          message: res.meta.msg
        })
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 打开分配角色对话框
    async openSetRoleDialog (userInfo) {
      this.setRoleDialogVisible = true
      this.setRoleUserInfo = userInfo
      this.setRoleCuurrentId = userInfo.id
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: res.meta.msg
        })
      }
      this.rolesList = res.data
    },
    // 取消设置角色
    cancelSetRole () {
      this.selectedRoleId = ''
      this.setRoleDialogVisible = false
    },
    // 分配角色
    async sureSetRole () {
      if (!this.selectedRoleId) return
      const res = await this.$http.put(`users/${this.setRoleCuurrentId}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'error',
          message: res.meta.msg
        })
      }
      this.$message({
        type: 'success',
        message: res.meta.msg
      })
      this.setRoleDialogVisible = false
      this.getUserList()
    }
  },
  watch: {
    userList: {
      handler () {
        this.loading = false
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
</style>
